package cmdb

import (
	"encoding/json"
	"errors"
	"fmt"
	"github.com/pkg/sftp"
	"golang.org/x/crypto/ssh"
	"io"
	"k8s-platform/config"
	"k8s-platform/db"
	"k8s-platform/model"
	"log"
	"os"
	"strings"
)

var Hostssh hostssh

type hostssh struct{}

// 判断用户是用过账号密码还是token登入
func getHostCredentials(user string, password string, CredentialID int64) func() (string, string) {
	var hostuser, hostpassword string
	var Credentialdata *model.Credential
	db.DB.First(&Credentialdata, CredentialID)
	Credentialuser := &Credentialdata.User
	Credentialpassword := &Credentialdata.Password

	if CredentialID > 0 {
		hostuser = *Credentialuser
		hostpassword = *Credentialpassword
	} else {
		hostuser = user
		hostpassword = password
	}
	return func() (string, string) {
		return hostuser, hostpassword
	}
}

func (*hostssh) Createssh(user string, password string, ip string, post string, command string, CredentialID int64) (host *model.HostServer, err error) {

	//用这个getHostCredentials函数返回一个闭包，这个闭包可以返回hostuser和hostpassword 通过调用这个闭包来获取hostuser和hostpassword的值
	getCredentials := getHostCredentials(user, password, CredentialID)
	hostuser, hostpassword := getCredentials()

	sshconfig := &ssh.ClientConfig{
		User: hostuser,
		Auth: []ssh.AuthMethod{
			ssh.Password(hostpassword),
		},
		HostKeyCallback: ssh.InsecureIgnoreHostKey(),
	}

	jenkinsConfigTest := &config.JenkinsConfigTest{}
	mysqlconfig, err := jenkinsConfigTest.ConfigTest()
	if err != nil {
		log.Fatalf("Failed to parse configuration: %v", err)
	}

	client, err := ssh.Dial("tcp", ip+":"+post, sshconfig)
	if err != nil {
		return nil, errors.New(fmt.Sprintf("账号或密码错误"))
	}
	session, err := client.NewSession()
	if err != nil {
		return nil, errors.New(fmt.Sprintf("创建session会话失败，请检查网络"))
	}

	//创建sftp会话
	sftpClient, err := sftp.NewClient(client)
	if err != nil {
		return nil, errors.New(fmt.Sprintf("创建sftp会话失败，请检查网络"))
	}
	defer sftpClient.Close()

	// 读取服务器环境文件内容
	srcFile, err := os.Open(config.FilePath)
	if err != nil {
		return nil, errors.New(fmt.Sprintf("获取脚本文件失败，请检查文件是否存在"))
	}

	//srcFile, err := os.Open(mysqlconfig.SrcFile)
	//if err != nil {
	//	return nil, errors.New(fmt.Sprintf("获取脚本文件失败，请检查文件是否存在"))
	//}
	defer srcFile.Close()

	dstFile, err := sftpClient.Create(mysqlconfig.DstFile)
	if err != nil {
		return nil, errors.New(fmt.Sprintf("目标路径失败，请检查文件路径"))
	}
	defer dstFile.Close()

	_, err = io.Copy(dstFile, srcFile)
	if err != nil {
		return nil, errors.New(fmt.Sprintf("复制文件失败，请检查文件路径是否存在"))
	}

	if command != "" {
	} else {
		command = "python /tmp/servermain.py"
	}

	hostdata, err := session.Output(command)
	if err != nil {
		return nil, errors.New(fmt.Sprintf("获取数据失败，请检查脚本文件是否错误"))
	}

	jsonOutput, err := json.Marshal(string(hostdata))
	if err != nil {
		log.Fatal(err)
	}

	jsonStr1 := strings.ReplaceAll(string(jsonOutput), "\\", "")
	jsonStr2 := strings.Trim(jsonStr1, "\"")
	jsonStr3 := strings.TrimSuffix(jsonStr2, "n")
	fmt.Println(jsonStr3)
	err = json.Unmarshal(([]byte(jsonStr3)), &host)
	if err != nil {
		return nil, err
	}
	client.Close()
	return host, nil
}
